import React from 'react'
import {Form, Modal, Input, Select, Tree, Button, Upload, Icon} from 'antd';
import API from "../../axios/api";
import {ProductType} from "../../utils/system-data";
import {beforeUpload} from '../../utils/utils'


import { func } from 'prop-types';
const config = require('../../config');

const { TextArea } = Input;

class ProductForm extends React.Component {
    constructor(props){
        super(props)
        this.state = {
            expandedKeys: [],
            autoExpandParent: true,
            checkedKeys: [],
            selectedKeys: [],
            treeData: [],
            editorContent: '',
            imgList: [],
            initHallList:[],
            // fileList: [],
            clear: false,
            previewVisible: false,
            previewImage: '',
            Hallid:'',
            fileList: [
                {
                    uid: '-1',
                    name: 'xxx.png',
                    status: 'done',
                    url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
                },
            ],
            Id: "",
            shareImage: []
        };
        this.handleSubmit = this.handleSubmit.bind(this)
        this.onBlurEditor = this.onBlurEditor.bind(this)
        this.onImgUploadChange = this.onImgUploadChange.bind(this)
    }

    onExpand = expandedKeys => {
        console.log('onExpand', expandedKeys);
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    };

    onCheck = checkedKeys => {
        console.log('onCheck', checkedKeys);
        this.setState({ checkedKeys });
    };

    onSelect = (selectedKeys, info) => {
        console.log('onSelect', info);
        this.setState({ selectedKeys });
    };
    componentDidMount() {
        const good  = this.props.good
        if(this.props.good){
            this.setState({
                Id: this.props.good.Id,
                shareImage: (good && good.ShareImage) || []
            })
        }
    }

    handleSubmit = (e) => {
        e && e.preventDefault()
        this.props.form.validateFields((err, values) => {
            if (!err) {
                // values.Id = this.state.Id
                values.shareImage = ''
                if(values.shareImageUpload && values.shareImageUpload.length > 0){
                    values.shareImage = values.shareImageUpload[0].response.Data
                }
                values.MainGoodsImageList = []
                if(values.upload && values.upload.length > 0){
                    let _list = [];
                    values.upload.map(item => {
                        _list.push({
                            ImageUrl: item.response.Data
                        })
                    })
                    values.MainGoodsImageList = _list
                }
                const { onOk } = this.props
                onOk && onOk(values)
                this.setState({
                    shareImage : []
                })
                this.props.form.resetFields()
                this.setState({imgList:[]})
            }
        })
    }

    handlerClose = (fn) => {
        this.props.form.resetFields()
        this.setState({ checkedKeys : []})
        fn()
    }

    getRolePermByRoleId =  async (Id) => {
        const parms = {
            Id
        }
        await API.getRolePermissionByRoleId(parms).then((res) => {
            if(res.Code === 200) {
                let checkedKeys = res.Data
                this.setState({
                    checkedKeys
                });
            }
        })
    }

    onBlurEditor(value){
        this.setState({
            editorContent: value
        })
    }

    onImgUploadChange(value){
        this.setState({
            imgList : value
        })
    }

    componentWillReceiveProps(nextProps, nextContext) {
        this.setState({
            imgList: []
        })
    }

    shareNormFile = e => {
        console.log('Upload event:', e);
        if (Array.isArray(e)) {
            return e;
        }
        this.setState({
            shareImage: e.fileList
        })
        return e && e.fileList;
    }

    normFile = e => {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    }
    onChange = (value) =>{
        this.initHallList(value)
    }

    onChangehall = (value) =>{
        this.setState({
            Hallid:value
        })
    }

    initHallList =  async (rudderId) => {
        let params = {
            ...API.config,
            RudderId:  rudderId || this.state.rudder.value,
        }
        await API.fetchHallPages(params).then((res) => {
            let initHallList = []
            if(res.Code === 200) {
                res.Data.List && res.Data.List.map(item => initHallList.push({value: item.Id, mean: item.HallName}))
                this.setState({
                    initHallList
                })
            }
        })
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const {
            modalKey,
            visible,
            title,
            fields,
            onCancel,
            onOk,
            okText,
            width,
            good,
            rudderList
        } = this.props
        let shareImageFile = (good && good.ShareImage) || []
        let defaultFileList = (good && good.GoodsImageList) || []
        let initHallList = this.state.initHallList
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 4 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
        }
     
        return (
            <Modal
                wrapClassName="form"
                key={modalKey}
                visible={visible}
                title={title}
                onCancel={onCancel}
                footer={null}
                width={width}
            >
                <Form onSubmit={this.handleSubmit}  {...formItemLayout} className="login-form">
                   
                    <Form.Item label="选择分舵">
                        {getFieldDecorator('RudderId', {
                            rules: [{ required: true, message: '分舵必选' }],
                        })(
                            <Select onChange={this.onChange}>
                                {
                                    rudderList && rudderList.map(item => {
                                        return (<option key={item.value} value={item.value}>{item.mean}</option>
                                        )
                                    })
                                }
                            </Select>,
                        )}
                    </Form.Item>


                    <Form.Item label="选择班级">
                    {getFieldDecorator('HallId', {
                        rules: [{ required: true, message: '班级必选' }],
                    })(
                        <Select onChange={this.onChangehall}>
                            {
                                initHallList && initHallList.map(item => {
                                    return (<option key={item.value} value={item.value}>{item.mean}</option>
                                    )
                                })
                            }
                        </Select>,
                    )}
                </Form.Item>

                    <Form.Item label="商户名称">
                        {getFieldDecorator('PayPosName', {
                            rules: [{ required: true, message: 'PayPosName必填！' }],
                        })(<Input/>)}
                    </Form.Item>
                  
                    <Form.Item label="商户号">
                        {getFieldDecorator('PayPosAppId', {
                            rules: [{ required: true, message: 'PayPosAppId必填！' }],
                        })(<Input/>)}
                    </Form.Item>
                 

                    <Form.Item label="商户密匙">
                        {getFieldDecorator('PayPosAppSecret', {
                            rules: [{ required: true, message: 'PayPosAppSecret必填！' }],
                        })(<Input/>)}
                    </Form.Item>
                    
            
                    <Form.Item label="支付API证书(p12)" >
                    {getFieldDecorator('shareImageUpload', {
                        valuePropName: 'fileList',
                        rules: [{ required: true, message: '必须上传证书文件！' }],
                        getValueFromEvent: this.shareNormFile,
                        initialValue: shareImageFile
                    })(
                        <Upload name="file"
                                        action = {config.default.apiURL + '/aboutapi/UploadPayPosCert?hallId=' + this.state.Hallid } 
                                        listType="picture"
                                        headers={
                                            {
                                                token : sessionStorage.getItem("token"),
                                            }
                                        }
                                >
                                    {(this.state.shareImage && this.state.shareImage.length >0) || (this.state.Hallid == '' || this.state.Hallid == undefined) ?  <br /> :
                                        <Button><Icon type="upload" />Click to upload</Button>
                                    }
                                </Upload>
                            )}
                        </Form.Item>


                    <div className="buttons">
                        {this.props.showCancel && <Button onClick={this.onCancel} >取消</Button>}
                        {!this.props.noBtn && <Button type="primary" htmlType="submit">{this.props.okText || '确定'}</Button>}
                    </div>
                </Form>
            </Modal>
        );
    }
}
let ArticleModalForm = Form.create()(ProductForm)

export default ArticleModalForm

